package com.thenie.chat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.thenie.chat.pojo.AddRequest;
import com.thenie.chat.pojo.User;
import com.thenie.chat.service.IAddRequestService;
import com.thenie.chat.service.IFriendService;
import com.thenie.chat.service.IUserService;
import com.thenie.chat.util.WebSocketUtil;
import com.thenie.chat.validator.CurrentUser;
import com.thenie.chat.vo.FriendRequestVo;
import com.thenie.chat.vo.RespBean;
import com.thenie.chat.vo.RespBeanEnum;
import com.thenie.chat.vo.UserInfoVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import static com.thenie.chat.config.RabbitmqConfig.*;
import static com.thenie.chat.controller.DialogSocketHandler.SESSION_MAP;

/**
 * <p>
 *  添加好友前端控制器
 * </p>
 *
 * @author thenie
 * @since 2022-06-03
 */
@RestController
@RequestMapping("/add-request")
public class AddRequestController {

    @Autowired
    private IFriendService friendService;

    @Autowired
    private IAddRequestService addRequestService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IUserService userService;

    /**
     * 添加好友
     * @param user
     * @param toId
     * @return
     */
    @PostMapping("/friend")
    public RespBean addFriend(@CurrentUser User user, Long toId){
        Long fromId = user.getId();
        FriendRequestVo friendRequestVo = new FriendRequestVo();
        BeanUtils.copyProperties(user,friendRequestVo);
        friendRequestVo.setFromId(fromId);
        friendRequestVo.setToId(toId);
        friendRequestVo.setSign(0);

        //判断是否是自己的好友
        if (friendService.isMyFriend(fromId,toId)){
            return RespBean.error(RespBeanEnum.NOT_RULES);
        }

        //若曾经加过对方且等待验证状态，还是保持原来状态返回
        AddRequest q1 = addRequestService.queryAddRequestFromMe(fromId, toId);
        if (q1!=null && q1.getSign()==0){
            return RespBean.success();
        }
        //判断对方是否加过我，若有0/1/2
        AddRequest q2 = addRequestService.queryAddRequestFromMe(toId, fromId);
        if (q2!=null && q2.getSign()==0){
            //修改标志为1
            addRequestService.updateSign(new AddRequest(null,toId,fromId,null,1));
            //生成Friend关系

            //通知双方刷新
        }

        //通过消息队列，异步处理
        //1.将记录保存到数据库
        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT_ADD_REQUEST,"save",friendRequestVo);
        //2.推送到接受者（在线/离线）
        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT_ADD_REQUEST,"send",friendRequestVo);

        return RespBean.success();
    }

    /**
     * 获取好友请求记录
     * @return
     */
    @GetMapping("/record/{id}")
    public RespBean friendRequestRecord(@PathVariable Long id){

        List<FriendRequestVo> list = addRequestService.queryFriendRequestList(id);

        return RespBean.success(list);
    }

    /**
     * 请求拒绝
     * @return
     */
    @PostMapping("/refused")
    public RespBean reqRefused(@CurrentUser User user,@RequestParam("fromId") Long fromId){
        int ok = addRequestService.updateSign(new AddRequest(null, fromId, user.getId(), null, 2));

        return RespBean.success(ok);
    }

    /**
     * 请求接受
     * @param user
     * @param fromId
     * @return
     */
    @PostMapping("/accept")
    public RespBean reqAccept(@CurrentUser User user,@RequestParam("fromId") Long fromId) throws IOException {
        //查找对方用户信息，并返回显示
        User toUser = userService.getUserById(fromId);
        UserInfoVo userInfoVo = new UserInfoVo();
        if (null == toUser){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        BeanUtils.copyProperties(toUser,userInfoVo);
        userInfoVo.setOnLine(0);

        //修改请求标记
        int ok = addRequestService.updateSign(new AddRequest(null, fromId, user.getId(), null, 1));
        //建立好友关系
        int change = friendService.createFriend(fromId, user.getId());
        if (change<1){
            return RespBean.error(RespBeanEnum.ERROR);
        }
        //若对方在线，通知对方并显示
        if (SESSION_MAP.containsKey(fromId.toString())){
            userInfoVo.setOnLine(1);

            WebSocketSession webSocketSession = SESSION_MAP.get(fromId.toString());
            UserInfoVo myUserInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(user,myUserInfoVo);
            myUserInfoVo.setOnLine(1);
            WebSocketUtil.sendNewFriendMsg(webSocketSession,myUserInfoVo);
        }

        return RespBean.success(userInfoVo);
    }
}
